<!--
 * @Author: yuqy
 * @Date: 2023-04-10 17:30:15
 * @LastEditors: yuqy
 * @LastEditTime: 2023-10-17 15:36:56
 * @Descripttion: -
-->
<template>
  <div class="rightBox">
    <div class="qrImg imgBox" @click="chooseLoginStyle" v-if="VUE_APP_TYPE == 'ODIN'">
      <img src="@/assets/img/login/二维码登录.png" alt v-if="loginStyle == 1">
      <img src="@/assets/img/login/账号登录 拷贝.png" alt v-if="loginStyle == 2">
    </div>
    <div class="loginBox" v-if="loginStyle == 1">
      <div class="tabsBox frow fjcsb faife">
        <p
          v-for="item in tabsList"
          :key="item.code"
          :class="activeTab == item.code ? 'activeClass tabClass ml5 ml5 cp' : 'tabClass ml5 ml5 cp'"
          @click="tabsClick(item)"
        >{{ item.name }}</p>
      </div>
      <div class="formBox_wrap">
        <!-- 账号登录 -->
        <transition
          name="transition"
          :enter-active-class="transitionEnter"
          :leave-active-class="transitionLeave"
        >
          <div class="formBox" key="login" v-if="activeTab == 1">
            <Form
              ref="loginForm"
              :model="loginForm"
              :rules="rules"
              @keydown.enter.native="_handleSubmit"
            >
              <FormItem prop="account">
                <Input
                  type="tel"
                  class="inputClass"
                  v-model="loginForm.account"
                  :maxlength="20"
                  placeholder="请输入手机号码"
                >
                  <template #prefix>
                    <img class="imgIcon" src="@/assets/img/login/phone.png">
                  </template>
                </Input>
              </FormItem>
              <FormItem prop="password">
                <Input
                  type="password"
                  class="inputClass"
                  :maxlength="18"
                  v-model="loginForm.password"
                  placeholder="请输入密码"
                  ref="submitPassword"
                >
                  <template #prefix>
                    <img class="imgIcon pwdIcon" src="@/assets/img/login/形状 681.png">
                  </template>
                </Input>
              </FormItem>
              <div class="frow fjcsb menuBox" v-if="VUE_APP_TYPE == 'ODIN'">
                <p @click="goRegister" class="cp menuItem">立即注册</p>
                <p @click="goForgetPwd" class="cp menuItem">忘记密码</p>
              </div>
              <div class="frow fjcsb menuBox" v-else>
                <p class="cp menuItem"></p>
              </div>
              <div class="btnBox fjcc frow" @click="_handleSubmit">
                <v-btn class="loginBtn" :loading="loading">登录</v-btn>
              </div>
            </Form>
          </div>
        </transition>
        <!-- 短信登录 -->
        <transition
          name="transition"
          :enter-active-class="transitionEnter"
          :leave-active-class="transitionLeave"
        >
          <div class="formBox" key="message" v-if="activeTab == 2">
            <Form
              ref="messageForm"
              :model="messageForm"
              :rules="rules"
              @keydown.enter.native="_handleSubmit"
            >
              <FormItem prop="phone">
                <Input
                  type="tel"
                  class="inputClass"
                  v-model="messageForm.phone"
                  :maxlength="20"
                  placeholder="请输入手机号码"
                >
                  <img class="imgIcon" src="@/assets/img/login/phone.png" slot="prefix">
                </Input>
              </FormItem>
              <FormItem prop="code">
                <Input
                  type="tel"
                  class="inputClass"
                  v-model="messageForm.code"
                  :maxlength="6"
                  placeholder="请输入验证码"
                >
                  <img class="imgIcon codeIcon" src="@/assets/img/login/验证码.png" slot="prefix">
                  <template #suffix>
                    <p class="getToken" @click="_checkPhone(messageForm)">{{ codeLabel }}</p>
                  </template>
                </Input>
              </FormItem>
              <div class="radioBox frow faic"></div>

              <div class="btnBox fjcc frow">
                <Button
                  @click="_handleSubmit"
                  class="loginBtn"
                  :loading="loading"
                  type="default"
                  long
                >登录</Button>
              </div>
            </Form>
          </div>
        </transition>

        <!-- 注册 -->
        <transition
          name="transition"
          :enter-active-class="transitionEnter"
          :leave-active-class="transitionLeave"
        >
          <div class="formBox" v-if="activeTab == 3 || activeTab == 5" key="register">
            <Form
              ref="registerForm"
              :model="registerForm"
              :rules="rules"
              @keydown.enter.native="_handleSubmit"
            >
              <FormItem prop="phone" v-if="registerForm.step == 1">
                <Input
                  type="tel"
                  class="inputClass"
                  v-model="registerForm.phone"
                  :maxlength="20"
                  placeholder="请输入手机号码"
                >
                  <img class="imgIcon" src="../../assets/img/login/手机号.png" slot="prefix">
                </Input>
              </FormItem>
              <FormItem prop="code" v-if="registerForm.step == 1">
                <Input
                  type="tel"
                  class="inputClass"
                  v-model="registerForm.code"
                  :maxlength="6"
                  placeholder="请输入验证码"
                >
                  <img class="imgIcon codeIcon" src="../../assets/img/login/验证码.png" slot="prefix">
                  <p
                    slot="suffix"
                    class="getToken"
                    @click="_checkPhone(registerForm)"
                  >{{ codeLabel }}</p>
                </Input>
              </FormItem>
              <FormItem prop="password" v-if="registerForm.step == 2">
                <Input
                  type="password"
                  class="inputClass"
                  v-model="registerForm.password"
                  :maxlength="20"
                  placeholder="请输入新密码(8-18位)"
                >
                  <img
                    class="imgIcon pwdIcon"
                    src="../../assets/img/login/形状 681.png"
                    slot="prefix"
                  >
                </Input>
              </FormItem>
              <FormItem prop="password2" v-if="registerForm.step == 2">
                <Input
                  type="password"
                  class="inputClass"
                  v-model="registerForm.password2"
                  :maxlength="20"
                  placeholder="请再次输入新密码"
                >
                  <img
                    class="imgIcon pwdIcon"
                    src="../../assets/img/login/形状 681.png"
                    slot="prefix"
                  >
                </Input>
              </FormItem>
              <div class="radioBox frow faic">
                <p @click="radioChange(registerForm)">
                  <Radio v-model="registerForm.radio"></Radio>
                </p>
                <p>
                  同意接受
                  <span class="urlClass cp" @click="goAgreement">《用户协议》</span>
                </p>
              </div>
              <div class="btnBox fjcc frow">
                <Button
                  @click="goBackStep"
                  class="goBackBtn mr20"
                  :loading="loading"
                  type="default"
                  long
                  v-if="registerForm.step == 2"
                >上一步</Button>
                <Button
                  @click="_handleSubmit"
                  class="loginBtn"
                  :loading="loading"
                  type="default"
                  long
                >确定</Button>
              </div>
              <div class="goLoginBox fjcc">
                <p class="goLogin fjcc cp" @click="goLogin">已有账号</p>
              </div>
            </Form>
          </div>
        </transition>

        <!-- 忘记密码 -->
        <transition
          name="transition"
          :enter-active-class="transitionEnter"
          :leave-active-class="transitionLeave"
        >
          <div class="formBox" v-if="activeTab == 4" key="forget">
            <Form
              ref="forgetPwdForm"
              :model="forgetPwdForm"
              :rules="rules"
              @keydown.enter.native="_handleSubmit"
            >
              <FormItem prop="phone" v-if="forgetPwdForm.step == 1">
                <Input
                  type="tel"
                  class="inputClass"
                  v-model="forgetPwdForm.phone"
                  :maxlength="20"
                  placeholder="请输入手机号码"
                >
                  <img class="imgIcon" src="../../assets/img/login/手机号.png" slot="prefix">
                </Input>
              </FormItem>
              <FormItem prop="code" v-if="forgetPwdForm.step == 1">
                <Input
                  type="tel"
                  class="inputClass"
                  v-model="forgetPwdForm.code"
                  :maxlength="6"
                  placeholder="请输入验证码"
                >
                  <img class="imgIcon codeIcon" src="../../assets/img/login/验证码.png" slot="prefix">
                  <p
                    slot="suffix"
                    class="getToken"
                    @click="_checkPhone(forgetPwdForm)"
                  >{{ codeLabel }}</p>
                </Input>
              </FormItem>
              <FormItem prop="password" v-if="forgetPwdForm.step == 2">
                <Input
                  type="password"
                  class="inputClass"
                  v-model="forgetPwdForm.password"
                  :maxlength="20"
                  placeholder="请输入新密码(8-18位)"
                >
                  <img
                    class="imgIcon pwdIcon"
                    src="../../assets/img/login/形状 681.png"
                    slot="prefix"
                  >
                </Input>
              </FormItem>
              <FormItem prop="password2" v-if="forgetPwdForm.step == 2">
                <Input
                  type="password"
                  class="inputClass"
                  v-model="forgetPwdForm.password2"
                  :maxlength="20"
                  placeholder="请再次输入新密码"
                >
                  <img
                    class="imgIcon pwdIcon"
                    src="../../assets/img/login/形状 681.png"
                    slot="prefix"
                  >
                </Input>
              </FormItem>
              <div class="radioBox frow faic">
                <p @click="radioChange(forgetPwdForm)">
                  <Radio v-model="forgetPwdForm.radio"></Radio>
                </p>
                <p>
                  同意接受
                  <span class="urlClass cp" @click="goAgreement">《用户协议》</span>
                </p>
              </div>
              <div class="btnBox fjcc frow">
                <Button
                  @click="_handleSubmit"
                  class="loginBtn"
                  :loading="loading"
                  type="default"
                  long
                >确定</Button>
              </div>
              <div class="goLoginBox fjcc">
                <p class="goLogin fjcc cp" @click="goLogin">已有账号</p>
              </div>
            </Form>
          </div>
        </transition>
      </div>
    </div>
    <div class="qrBox fcol faic" v-if="loginStyle == 2">
      <p class="qrTitle fjcc faic">请使用{{ qrStyle.name }}扫码登录</p>
      <div class="qrImgBox">
        <Spin size="large" fix :show="spinCodeLoaing"></Spin>
        <transition
          name="transition"
          enter-active-class="animate__animated animate__zoomIn"
          leave-active-class="animate__animated animate__zoomOut"
        >
          <div class="imgBox" v-if="qrStyle.name == '钉钉' && dingQrSrc" key="钉钉">
            <img :src="dingQrSrc" class="qrImg">
            <img src="@/assets/img/login/钉钉.png" alt class="logoImg">
          </div>
        </transition>

        <transition
          name="transition"
          enter-active-class="animate__animated animate__zoomIn"
          leave-active-class="animate__animated animate__zoomOut"
        >
          <div class="imgBox" v-if="qrStyle.name == '微信' && wxQrSrc" key="微信">
            <img :src="wxQrSrc" class="qrImg">
            <img src="@/assets/img/login/微信 拷贝.png" alt class="logoImg">
          </div>
        </transition>
      </div>
      <div class="frow fjcc qrListBox">
        <div
          v-for="item in qrList"
          :key="item.code"
          class="qrItem fcol fjcc cp"
          @click="changeQr(item)"
        >
          <img :src="item.img" alt class="qrImgClass">
          <p>{{ item.name }}</p>
        </div>
      </div>
    </div>
  </div>
</template>
<script >
import { ref } from "vue";
import { Form, Input, FormItem, Button, Radio, Spin, Message } from "view-ui-plus";
import dingding from "@/assets/img/login/钉钉.png";
import weixin from "@/assets/img/login/weixin.png";
import $ from 'jquery';
import { mapActions } from 'vuex';
import {
  getLoginWechatQrcode,
  postLoginWechat,
  getLoginDingtalkQrcode,
  getLoginDingtalkCode,
  postLoginDingtalk,
  postLoginDingtalkQrcodeState,
  postLoginRegister,
  getLoginRegister,
  getLoginSmsCodeSend,
  postLoginSmsCodeVerify,
  postLoginSms,
  putLoginPasswordReset,
  postLoginDingtalkRegister,
  postLoginWechatRegister,
  postLoginDingtalkBind,
  postLoginWechatBind,
  putBindPhone
} from '@/api/user';
// import { setTimeout } from 'timers';
let tabsList = [{ name: "账号登录", code: 1 }, { name: "短信登录", code: 2 }];
export default {
  setup() {},
  data() {
    return {
      tabsList,
      dingQrSrc: "",
      wxQrSrc: "",
      spinCodeLoaing: false,
      qrList: [
        {
          name: "钉钉",
          code: 1,
          img: dingding
        },
        {
          name: "微信",
          code: 2,
          img: weixin
        }
      ],
      qrStyle: { name: "微信", code: 2 },
      activeTab: 1,
      loading: false,
      rules: {},
      loginStyle: 1,
      loginForm: {
        account: "",
        password: ""
      },
      messageForm: {
        password: "",
        phone: "",
        phoneToken: "",
        radio: false
      },
      registerForm: {
        password: "",
        password2: "",
        phone: "",
        phoneToken: "",
        radio: false,
        codeType: 3, // 1变更信息 2重置 3身份验证
        step: 1, // 表单步骤标识
        bind: 0, // 钉钉或微信绑定标识
        login: 0 // 钉钉或微信注册标识
      },
      forgetPwdForm: {
        password: "",
        password2: "",
        phone: "",
        phoneToken: "",
        radio: false,
        codeType: 3,
        step: 1
      },
      wxQrData: {},
      dingQrData: {},
      userData: { dataType: 0 }, // 0注册 1钉钉 2微信
      codeLabel: "获取验证码",
      codeTime: 60,
      codeTimer: null,
      transitionEnter: "animate__fast animate__animated animate__fadeInRight",
      transitionLeave: "animate__fast animate__animated animate__fadeOutLeft",
      showIp: false,
      showConsoleNum: 0,
      isMini: false,
      isWeb: false,
      unBindToken: null
    };
  },
  components: {
    Form,
    Input,
    FormItem,
    Button,
    Radio,
    Spin
  },
  watch: {
    activeTab(newValue, oldValue) {
      if ((oldValue == 1 || oldValue == 4 || oldValue == 3) && newValue == 2) {
        // 账号|| 忘记||注册=>短信
        this.transitionEnter =
          "animate__fast animate__animated animate__fadeInRight";
        this.transitionLeave =
          "animate__fast animate__animated animate__fadeOutLeft";
      } else if (
        oldValue == 2 &&
        (newValue == 1 || newValue == 4 || newValue == 3)
      ) {
        // 短信=>账号||忘记||注册
        this.transitionEnter =
          "animate__fast animate__animated animate__fadeInLeft";
        this.transitionLeave =
          "animate__fast animate__animated animate__fadeOutRight";
      } else if (oldValue == 1 && (newValue == 3 || newValue == 4)) {
        // 账号=>注册||忘记
        this.transitionEnter =
          "animate__fast animate__animated animate__fadeInUp";
        this.transitionLeave =
          "animate__fast animate__animated animate__fadeOutUp";
      } else if (
        (oldValue == 3 || oldValue == 4) &&
        (newValue == 1 || newValue == 2)
      ) {
        // 注册||忘记=>账号||短信
        this.transitionEnter =
          "animate__fast animate__animated animate__fadeInDown";
        this.transitionLeave =
          "animate__fast animate__animated animate__fadeOutDown";
      } else if (oldValue == 1 && newValue == 5) {
        // 注册||忘记=>账号||短信
        this.transitionEnter =
          "animate__fast animate__animated animate__fadeInDown";
        this.transitionLeave =
          "animate__fast animate__animated animate__fadeOutDown";
      }
    }
  },
  mounted() {
    if (this.VUE_APP_TYPE == "MID") {
      this.tabsList.pop();
    }
    // 主动清空token
    this.$store.commit('user/updateToken', '')
  },
  methods: {
    ...mapActions('user', ['getUserInfo', 'postLogin']),
    chooseLoginStyle() {},
    tabsClick({ code }) {
      this.activeTab = code;
    },
    async chooseLoginStyle () {
      let loginStyle = this.loginStyle
      this.loginStyle = 0
      await this.$nextTick();
      this.loginStyle = loginStyle == 1?2:1;
      if (this.loginStyle == 2) {
        this.getWxQrCode()
      }
    },
    changeQr (item) {
      this.qrStyle = item
      if (item.code == 2) {
        this.getWxQrCode()
      } else {
        this.getDingQrCode()
      }
    },
    // 获取微信二维码
    async getWxQrCode () {
      this.spinCodeLoaing = true
      let { data, success } = await getLoginWechatQrcode()
      this.spinCodeLoaing = false
      if (!success) return;
      this.wxQrSrc = data.qrCode
      this.wxQrData = data
      this.getWxCode()
      this.qrStyle = { name: '微信', code: 2 }
    },

    // 获取钉钉二维码
    async getDingQrCode () {
      this.spinCodeLoaing = true
      let { data, success } = await getLoginDingtalkQrcode()
      this.spinCodeLoaing = false
      if (!success) return;
      this.dingQrSrc = data.qrCode
      this.dingQrData = data
      this.getDingCode()
      this.qrStyle = { name: '钉钉', code: 1 }
    },

    // 微信效验 需要实时监测  用户状态
    getWxCode (d) {
      if (this.qrStyle.code != 2) return
      let that = this
      $.ajax({
        type: 'GET',
        url: that.wxQrData.qrCodeStateQueryUrl + (d ? '&last=' + d : ''),
        dataType: 'script', // 这里是script类型
        cache: !1,
        timeout: 30000,
        success: function (d, e, f) {
          var g = window.wx_errcode // 返回的格式是script 内容是 window.wx_errcode=408;window.wx_code='';
          switch (g) {
            case 405: // 如果是405证明用户已经同意授权登录 用js重定向并带上code
              that.postLoginWechat(window.wx_code)
              break
            case 404:
              that.loginStyle == 2 && setTimeout(that.getWxCode, 100, g)
              break
            case 403:
              that.loginStyle == 2 && setTimeout(that.getWxCode, 100, g)
              break
            case 402:
            case 500:
              that.getWxQrCode()
              break
            case 408:
              that.loginStyle == 2 && setTimeout(that.getWxCode, 100)
          }
        },
        error: function (b, c, d) {
          var e = window.wx_errcode
          e == 408 && that.loginStyle == 2 ? setTimeout(that.getWxCode, 100) : setTimeout(that.getWxCode, 100, e)
        }
      })
    },
    // 用户同意授权，开始登录
    async postLoginWechat (code) {
      let { data, success } = await postLoginWechat({ code, state: this.wxQrData.state })
      this.userData = data
      this.userData.dataType = 2
      // 注册状态：0未注册 1已注册
      if (data.registerStatus == 0) {
        // this.$Notice.warning({ title: '提示', desc: '暂未绑定手机号,请绑定手机号' })
        this.$Message.warning({ content: '暂未绑定手机号,请绑定手机号' })
        this.getWxQrCode()
        this.loginStyle = 1
        this.goRegister()
      } else if (data.registerStatus == 1) {
        this.loginSuccess(data.token)
      }
    },
    /**
     * @name: 钉钉效验 需要实时监测  用户状态
     * @msg: 
     * @return {*}
     */    
    async getDingCode () {
      if (this.qrStyle.code != 1) return
      let { data } = await postLoginDingtalkQrcodeState({
        gotoUrl: this.dingQrData.gotoUrl,
        pdmToken: this.dingQrData.pdmToken,
        qrCodeUid: this.dingQrData.qrCodeUid,
      })
      let g = data.code
      switch (g) {
        case '11041':
          // 已扫码
          if (!data.success) {
            this.loginStyle == 2 && setTimeout(this.getDingCode, 100)
          }
          break
        case '11021':
          // 扫码登录失败，请刷新重试或选择其他登录方式
          this.loginStyle == 2 && setTimeout(this.getDingCode, 100)
          break
        case '11019':
          // 二维码已失效，请刷新二维码重新扫描
          this.getDingQrCode()
          break

        default:
          // 已扫码已确认 code为null
          if (data.success) {
            this.getLoginDingtalkCode(data.data)
          } else {
            this.loginStyle == 2 && setTimeout(this.getDingCode, 100)
          }
          break
      }
    },
    getLoginDingtalkCode (url) {
      getLoginDingtalkCode({ base64Url: encodeBase64(url) }).then((res) => {
        this.postLoginDingtalk(res)
      })
    },
    // 钉钉登录
    postLoginDingtalk (code) {
      postLoginDingtalk({ code: code, state: this.dingQrData.state }).then((res) => {
        this.userData = res
        this.userData.dataType = 1
        // 注册状态：0未注册 1已注册
        if (res.registerStatus == 0) {
          this.loginStyle = 1
          // this.$Notice.warning({ title: '提示', desc: '暂未绑定手机号,请绑定手机号' })
          this.$Message.warning({ content: '暂未绑定手机号,请绑定手机号' })
          this.getDingQrCode()
          this.goRegister()
        } else if (res.registerStatus == 1) {
          this.loginSuccess(res.token)
        }
      })
    },
    /**
     * @name: 登录
     * @msg: 
     * @return {*}
     */    
    _handleSubmit () {
      if (this.activeTab == 1) {
        this.handleSubmit()
      } else if (this.activeTab == 2) {
        this.handleSubmitMsg()
      } else if (this.activeTab == 3) {
        this.handleRegister()
      } else if (this.activeTab == 4) {
        this.handleForgetPwd()
      } else if (this.activeTab == 5) {
        this.handleAccountBind()
      }
    },
    // 账号登录
    handleSubmit () {
      this.$refs.submitPassword.blur()
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          const account = this.loginForm.account.trim()
          const password = this.loginForm.password.trim()
          if (!account) {
            return Message.error({ content: '请先填写手机号' })
          }
          if (!password) {
            return Message.error({ content: '请先填写密码' })
          }
          this.loading = true
          let { token } = await this.postLogin({ account, password })
          if (!token) return this.loading = false;
          localStorage.setItem('account', account)
          localStorage.setItem('password', password)
          this.loginSuccess(token)
        }
      })
    },
    /**
     * @name: 登录成功
     * @msg: 
     * @return {*}
     */    
    async loginSuccess (token) {
      let userData = await this.getUserInfo()
      // 获取用户信息，如果没有绑定手机号，需要提示用户去绑定手机号,此时需要先把token置空，待手机号绑定以后才能存在本地
      if (!userData.phone) {
        // 主动去绑定手机号，（目前逻辑暂时直接拒绝登入）
        this.$store.commit('updateToken', '')
        this.loading = false
        return Message.error({ content: '您的账号未绑定手机号，请联系管理员' })
      }
      if (userData.inspectStatus == 1) {
        this.$store.commit('updateToken', '')
        this.loading = false
        return false;
      }
      Message.success({ content: '登录成功' })
      this.loading = false
      setTimeout(() => {
        this.$router.push('home')
      }, 100)
    }
  }
};
</script>
<style scoped lang="less">
@import url("./less/login.less");
</style>
